<a href='https://github.com/angular/angular.js/edit/v1.6.x/docs/content/tutorial/step_07.ngdoc?message=docs(tutorial%2F7 - XHR & Dependency Injection)%3A%20describe%20your%20change...' class='improve-docs btn btn-primary'><i class="glyphicon glyphicon-edit">&nbsp;</i>Improve this Doc</a>


<ul doc-tutorial-nav="7"></ul>


<p>Enough of building an app with three phones in a hard-coded dataset! Let&#39;s fetch a larger dataset
from our server using one of Angular&#39;s built-in <a href="guide/services">services</a> called
<a href="api/ng/service/$http">$http</a>. We will use Angular&#39;s <a href="guide/di">dependency injection (DI)</a> to provide
the service to the <code>phoneList</code> component&#39;s controller.</p>
<ul>
<li>There is now a list of 20 phones, loaded from the server.</li>
</ul>
<div doc-tutorial-reset="7"></div>


<h2 id="data">Data</h2>
<p>The <code>app/phones/phones.json</code> file in our project is a dataset that contains a larger list of phones,
stored in JSON format.</p>
<p>Following is a sample of the file:</p>
<pre><code class="lang-json">[
  {
    &quot;age&quot;: 13,
    &quot;id&quot;: &quot;motorola-defy-with-motoblur&quot;,
    &quot;name&quot;: &quot;Motorola DEFY\u2122 with MOTOBLUR\u2122&quot;,
    &quot;snippet&quot;: &quot;Are you ready for everything life throws your way?&quot;
    ...
  },
  ...
]
</code></pre>
<h2 id="component-controller">Component Controller</h2>
<p>We will use Angular&#39;s <a href="api/ng/service/$http">$http</a> service in our controller for making an HTTP request to
our web server to fetch the data in the <code>app/phones/phones.json</code> file. <code>$http</code> is just one of
several built-in <a href="guide/services">Angular services</a> that handle common operations in web
applications. Angular injects these services for you, right where you need them.</p>
<p>Services are managed by Angular&#39;s <a href="guide/di">DI subsystem</a>. Dependency injection helps to make
your web applications both well-structured (e.g. separate entities for presentation, data, and
control) and loosely coupled (dependencies between entities are not resolved by the entities
themselves, but by the DI subsystem). As a result, applications are easier to test as well.</p>
<p><br />
<strong><code>app/phone-list/phone-list.component.js:</code></strong></p>
<pre><code class="lang-js">angular.
  module(&#39;phoneList&#39;).
  component(&#39;phoneList&#39;, {
    templateUrl: &#39;phone-list/phone-list.template.html&#39;,
    controller: function PhoneListController($http) {
      var self = this;
      self.orderProp = &#39;age&#39;;

      $http.get(&#39;phones/phones.json&#39;).then(function(response) {
        self.phones = response.data;
      });
    }
  });
</code></pre>
<p><code>$http</code> makes an HTTP GET request to our web server, asking for <code>phones.json</code> (the URL is relative
to our <code>index.html</code> file). The server responds by providing the data in the JSON file.
(The response might just as well have been dynamically generated by a backend server. To the
browser and our app, they both look the same. For the sake of simplicity, we will use JSON files
in this tutorial.)</p>
<p>The <code>$http</code> service returns a <a href="api/ng/service/$q">promise object</a>, which has a <code>then()</code> method. We call
this method to handle the asynchronous response and assign the phone data to the controller, as a
property called <code>phones</code>. Notice that Angular detected the JSON response and parsed it for us into 
the <code>data</code> property of the <code>response</code> object passed to our callback!</p>
<p>Since we are making the assignment of the <code>phones</code> property in a callback function, where the <code>this</code>
value is not defined, we also introduce a local variable called <code>self</code> that points back to the
controller instance.</p>
<p>To use a service in Angular, you simply declare the names of the dependencies you need as arguments
to the controller&#39;s constructor function, as follows:</p>
<pre><code class="lang-js">function PhoneListController($http) {...}
</code></pre>
<p>Angular&#39;s dependency injector provides services to your controller, when the controller is being
constructed. The dependency injector also takes care of creating any transitive dependencies the
service may have (services often depend upon other services).</p>
<p>Note that the names of arguments are significant, because the injector uses these to look up the
dependencies.</p>
<p><img  class="diagram" src="img/tutorial/tutorial_05.png"></p>
<h3 id="-prefix-naming-convention"><code>$</code>-prefix Naming Convention</h3>
<p>You can create your own services, and in fact we will do exactly that a few steps down the road. As
a naming convention, Angular&#39;s built-in services, Scope methods and a few other Angular APIs have a
<code>$</code> prefix in front of the name.</p>
<p>The <code>$</code> prefix is there to namespace Angular-provided services. To prevent collisions it&#39;s best to
avoid naming your services and models anything that begins with a <code>$</code>.</p>
<p>If you inspect a Scope, you may also notice some properties that begin with <code>$$</code>. These properties
are considered private, and should not be accessed or modified.</p>
<h3 id="a-note-on-minification">A Note on Minification</h3>
<p>Since Angular infers the controller&#39;s dependencies from the names of arguments to the controller&#39;s
constructor function, if you were to <a href="https://en.wikipedia.org/wiki/Minification_(programming)">minify</a> the JavaScript code for the
<code>PhoneListController</code> controller, all of its function arguments would be minified as well, and the
dependency injector would not be able to identify services correctly.</p>
<p>We can overcome this problem by annotating the function with the names of the dependencies, provided
as strings, which will not get minified. There are two ways to provide these injection annotations:</p>
<ul>
<li><p>Create an <code>$inject</code> property on the controller function which holds an array of strings.
Each string in the array is the name of the service to inject for the corresponding parameter.
In our example, we would write:</p>
<pre><code class="lang-js">function PhoneListController($http) {...}
PhoneListController.$inject = [&#39;$http&#39;];
...
.component(&#39;phoneList&#39;, {..., controller: PhoneListController});
</code></pre>
</li>
<li><p>Use an inline annotation where, instead of just providing the function, you provide an array.
This array contains a list of the service names, followed by the function itself as the last item
of the array.</p>
<pre><code class="lang-js">function PhoneListController($http) {...}
...
.component(&#39;phoneList&#39;, {..., controller: [&#39;$http&#39;, PhoneListController]});
</code></pre>
</li>
</ul>
<p>Both of these methods work with any function that can be injected by Angular, so it&#39;s up to your
project&#39;s style guide to decide which one you use.</p>
<p>When using the second method, it is common to provide the constructor function inline, when
registering the controller:</p>
<pre><code class="lang-js">.component(&#39;phoneList&#39;, {..., controller: [&#39;$http&#39;, function PhoneListController($http) {...}]});
</code></pre>
<p>From this point onwards, we are going to use the inline method in the tutorial. With that in mind,
let&#39;s add the annotations to our <code>PhoneListController</code>:</p>
<p><br />
<strong><code>app/phone-list/phone-list.component.js</code></strong></p>
<pre><code class="lang-js">angular.
  module(&#39;phoneList&#39;).
  component(&#39;phoneList&#39;, {
    templateUrl: &#39;phone-list/phone-list.template.html&#39;,
    controller: [&#39;$http&#39;,
      function PhoneListController($http) {
        var self = this;
        self.orderProp = &#39;age&#39;;

        $http.get(&#39;phones/phones.json&#39;).then(function(response) {
          self.phones = response.data;
        });
      }
    ]
  });
</code></pre>
<h1 id="testing">Testing</h1>
<p>Because we started using dependency injection and our controller has dependencies, constructing the
controller in our tests is a bit more complicated. We could use the <code>new</code> operator and provide the
constructor with some kind of fake <code>$http</code> implementation. However, Angular provides a mock <code>$http</code>
service that we can use in unit tests.  We configure &quot;fake&quot; responses to server requests by calling
methods on a service called <code>$httpBackend</code>:</p>
<p><br />
<strong><code>app/phone-list/phone-list.component.spec.js</code>:</strong></p>
<pre><code class="lang-js">describe(&#39;phoneList&#39;, function() {

  beforeEach(module(&#39;phoneList&#39;));

  describe(&#39;controller&#39;, function() {
    var $httpBackend, ctrl;

    // The injector ignores leading and trailing underscores here (i.e. _$httpBackend_).
    // This allows us to inject a service and assign it to a variable with the same name
    // as the service while avoiding a name conflict.
    beforeEach(inject(function($componentController, _$httpBackend_) {
      $httpBackend = _$httpBackend_;
      $httpBackend.expectGET(&#39;phones/phones.json&#39;)
                  .respond([{name: &#39;Nexus S&#39;}, {name: &#39;Motorola DROID&#39;}]);

      ctrl = $componentController(&#39;phoneList&#39;);
    }));

    ...

  });

});
</code></pre>
<div class="alert alert-info">
  <strong>Note:</strong> Because we loaded Jasmine and <code>angular-mocks.js</code> in our test environment, we got two
  helper methods <a href="api/ngMock/function/angular.mock.module">module</a> and <a href="api/ngMock/function/angular.mock.inject">inject</a> that we
  can use to access and configure the injector.
</div>

<p>We created the controller in the test environment, as follows:</p>
<ul>
<li><p>We used the <code>inject()</code> helper method to inject instances of
<a href="api/ngMock/service/$componentController">$componentController</a> and <a href="api/ng/service/$httpBackend">$httpBackend</a>
services into Jasmine&#39;s <code>beforeEach()</code> function. These instances come from an injector which is
recreated from scratch for every single test. This guarantees that each test starts from a well
known starting point and each test is isolated from the work done in other tests.</p>
</li>
<li><p>We called the injected <code>$componentController</code> function passing the name of the <code>phoneList</code>
component (whose controller we wanted to instantiate) as a parameter.</p>
</li>
</ul>
<p>Because our code now uses the <code>$http</code> service to fetch the phone list data in our controller, before
we create the <code>PhoneListController</code>, we need to tell the testing harness to expect an incoming
request from the controller. To do this we:</p>
<ul>
<li><p>Inject the <code>$httpBackend</code> service into the <code>beforeEach()</code> function. This is a
<a href="api/ngMock/service/$httpBackend">mock version</a> of the service that in a production environment
facilitates all XHR and JSONP requests. The mock version of this service allows us to write tests
without having to deal with native APIs and the global state associated with them — both of which
make testing a nightmare. It also overcomes the asynchronous nature of these calls, which would
slow down unit tests.</p>
</li>
<li><p>Use the <code>$httpBackend.expectGET()</code> method to train the <code>$httpBackend</code> service to expect an
incoming HTTP request and tell it what to respond with. Note that the responses are not returned
until we call the <code>$httpBackend.flush()</code> method.</p>
</li>
</ul>
<p>Now we will make assertions to verify that the <code>phones</code> property doesn&#39;t exist on the controller 
before the response is received:</p>
<pre><code class="lang-js">it(&#39;should create a `phones` property with 2 phones fetched with `$http`&#39;, function() {
  expect(ctrl.phones).toBeUndefined();

  $httpBackend.flush();
  expect(ctrl.phones).toEqual([{name: &#39;Nexus S&#39;}, {name: &#39;Motorola DROID&#39;}]);
});
</code></pre>
<ul>
<li><p>We flush the request queue in the browser by calling <code>$httpBackend.flush()</code>. This causes the
promise returned by the <code>$http</code> service to be resolved with the trained response. See
<a href="api/ngMock/service/$httpBackend#flushing-http-requests">Flushing HTTP requests</a> in the mock
<code>$httpBackend</code> documentation for a full explanation of why this is necessary.</p>
</li>
<li><p>We make the assertions, verifying that the <code>phones</code> property now exists on the controller.</p>
</li>
</ul>
<p>Finally, we verify that the default value of <code>orderProp</code> is set correctly:</p>
<pre><code class="lang-js">it(&#39;should set a default value for the `orderProp` property&#39;, function() {
  expect(ctrl.orderProp).toBe(&#39;age&#39;);
});
</code></pre>
<p>You should now see the following output in the Karma tab:</p>
<pre><code>Chrome 49.0: Executed 2 of 2 SUCCESS (0.133 secs / 0.097 secs)
</code></pre>
<h1 id="experiments">Experiments</h1>
<div></div>

<ul>
<li><p>At the bottom of <code>phone-list.template.html</code>, add a
<code>&lt;pre&gt;{{$ctrl.phones | filter:$ctrl.query | orderBy:$ctrl.orderProp | json}}&lt;/pre&gt;</code> binding to see
the list of phones displayed in JSON format.</p>
</li>
<li><p>In the <code>PhoneListController</code> controller, pre-process the HTTP response by limiting the number of
phones to the first 5 in the list. Use the following code in the <code>$http</code> callback:</p>
<pre><code class="lang-js">self.phones = response.data.slice(0, 5);
</code></pre>
</li>
</ul>
<h1 id="summary">Summary</h1>
<p>Now that you have learned how easy it is to use Angular services (thanks to Angular&#39;s dependency
injection), go to <a href="tutorial/step_08">step 8</a>, where you will add some thumbnail images of phones and
some links.</p>
<ul doc-tutorial-nav="7"></ul>





